#coding:utf-8
from BeautifulSoup import BeautifulSoup
import urllib2,os
import hashlib
from models import *
from django.utils.hashcompat import md5_constructor
from django.views.decorators.cache import cache_page,never_cache,cache_control
from django.db.models import Sum, Count
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib import auth, messages
from django.db import transaction
from models import *
from forms import *
from utils import *

@transaction.commit_on_success
def init_apps(request):
    #req = urllib2.Request("http://store.ovi.com.cn/?lid=storeherobtnnli&cid=ovistore-fw-ilc-herobtnnli-acq-na-ovicom-g0-na-1")   
    #page = urllib2.urlopen(req) 
    #print u"数据初始开始"
    page = open("script/ovi.html").read()
    bf = BeautifulSoup(page)
    bf.prettify("utf-8")
    softList =  bf.findAll("li",{"class":"entity nth-child-odd "})
    apps = []
    idd = 100
    for soft in softList:
        idd += 1
        thumb_a =  soft.find("a" ,{"class":"thumb"})
        thumb_img = thumb_a.find("img")['src']
        title = soft.find("h4" ).find("a").string
        typ =  soft.find("span" ).string
        auther_el = soft.find("p" ,{"class":"beforeRating"}).find("a")
        auther = auther_el.string
        auther_url = auther_el['href']
        summary = soft.find("p" ,{"class":"summary"}).string
    
        image = "media/upload/nokia/%s.png"%idd

        data = urllib2.urlopen(thumb_img).read()
        imgfile = open(image,"wb")
        imgfile.write(data)
        imgfile.close()
        
        
#        app['image'] = image
#        app['title'] = title
#        app['tag'] = typ
#        app['auther'] = auther
#        app['auther_url'] = auther_url
#        app['summary'] = summary
#        apps.append(app)
        
         #insert db
        tag = AppTag()
        tag.name = typ
        tag.save()
        
        app = App.objects.create()
        app.user = request.user
        app.name = title
        app.version = 'N/A'
        app.app_url = thumb_a['href']
        app.auther = auther
        app.auther_url = auther_url
        app.thumb = image
        app.audit = True
        app.score = 0
        app.tags.add(tag)
        app.save()
       # print u"数据初始完毕"
       
    return HttpResponse("ok")

        


